import { Component, OnInit, ViewChild, ElementRef, Input, OnChanges } from '@angular/core';
import * as echarts from 'echarts';
import { ResizeService } from '../../services/resize.service';
import { tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { EChartOptionExp } from './e-chart-option-exp.module';

@Component({
	selector: 'm-status-card',
	templateUrl: './status-card.component.html',
	styleUrls: ['./status-card.component.scss'],
})
export class StatusCardComponent implements OnInit, OnChanges {
	@ViewChild('canvasContainer') canvasContainer: ElementRef<HTMLDivElement>;
	@Input() name: string;
	@Input() value: Array<{ name: string; value: number; color: string }> = [];
	@Input() color: string[];
	$resize: Observable<any>;
	chart: echarts.ECharts;
	constructor(private resizeService: ResizeService) {}

	ngOnInit() {
		this.chart = echarts.init(this.canvasContainer.nativeElement);
		this.$resize = this.resizeService.$WindowResize.pipe(tap(() => this.chart.resize()));
		this.chart.setOption(defaultOption);
	}
	ngOnChanges() {
		if (!this.value) {
			return;
		}
		this.chart.setOption({
			color: this.color,
			legend: {
				data: this.value.map(v => v.name),
			},
			series: [
				{
					name: this.name,
					data: [{ ...this.value[0], ...showLabel }, ...this.value.slice(1)],
				},
			],
		});
	}
}
const showLabel = {
	label: {
		normal: {
			show: true,
		},
	},
};
const defaultOption: EChartOptionExp = {
	// 颜色
	// color: ['green', 'red', 'gray'],
	// 悬浮
	tooltip: {
		trigger: 'item',
		formatter: '{a} <br/>{b}: {c} ({d}%)',
	},
	// 图例
	legend: {
		orient: 'vertical',
		x: 'right',
		y: 'center',
		data: ['已更新', '未更新', '未知'],
	},
	series: [
		{
			name: 'pie',
			type: 'pie',
			center: ['30%', '50%'],
			radius: ['60%', '80%'],
			avoidLabelOverlap: false,
			label: {
				normal: {
					show: false,
					position: 'center',
					formatter: '{b}\n{c}',
					textStyle: {
						fontSize: '20',
						fontWeight: 'bold',
					},
				},
				emphasis: {
					show: true,
					formatter: '{b}\n{c}',
					borderRadius: 100,
					backgroundColor: 'white',
					padding: 15,
					textStyle: {
						fontSize: '20',
						fontWeight: 'bold',
					},
				},
			},
			labelLine: {
				normal: {
					show: false,
				},
			},
		},
	],
};
